package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author wmz
 * @date 2024/1/30 14:25
 * @description 定时任务处理
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单，每隔一分钟执行一次
     */
    @Scheduled(cron = "0 * * * * ?") //每分钟触发一次
    public void processTimeOutOrder(){
        log.info("处理超时订单：{}", LocalDateTime.now());
        //超时订单：1.订单状态为待支付 2.经过超过15分钟
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        //查询是否存在此类订单
        List<Orders> ordersList = orderMapper.excuteOrderByMinutes(Orders.PENDING_PAYMENT,time);
        if(!CollectionUtils.isEmpty(ordersList)){
            ordersList.forEach(orders -> {
                orders.setCancelReason("订单超时未支付");
                orders.setCancelTime(LocalDateTime.now());
                orders.setStatus(Orders.CANCELLED);
                orderMapper.update(orders);
            });
        }

    }

    /**
     * 凌晨一点，自动处理一直处于配送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨一点触发
    public void processDeliveryOrder(){
        log.info("处理处于配送中的订单：{}", LocalDateTime.now());
        //超时订单：1.订单状态为配送中 2.每天凌晨一点
        LocalDateTime time = LocalDateTime.now().minusMinutes(60);
        //查询是否存在此类订单
        List<Orders> ordersList = orderMapper.excuteOrderByMinutes(Orders.DELIVERY_IN_PROGRESS,time);
        if(!CollectionUtils.isEmpty(ordersList)) {
            ordersList.forEach(orders -> {
                orders.setDeliveryTime(LocalDateTime.now());
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }
    }
}
